package com.henry.chatkit.messages

import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.henry.chatkit.*


abstract class MessageLayoutUI : RecyclerView {

    protected var mAdapter: MessageListAdapter? = null
    protected var mOnItemClickListener: OnItemClickListener? = null
    protected var mHandler: OnLoadMoreHandler? = null
    protected var mEmptySpaceClickListener: OnEmptySpaceClickListener? = null
    protected var mOnPopActionClickListener: OnPopActionClickListener? = null

    protected var mPopActions = mutableListOf<PopMenuAction>()
    protected var mMorePopActions = mutableListOf<PopMenuAction>()

    constructor(context: Context) : super(context) {
        init()
    }
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init()
    }
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        init()
    }

    private fun init() {
        isLayoutFrozen = false
        setItemViewCacheSize(0)
        setHasFixedSize(true)
        isFocusableInTouchMode = false
        val linearLayoutManager = LinearLayoutManager(context)
        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        layoutManager = linearLayoutManager

    }

    open fun findViewByPosition(position: Int): View? {
        return layoutManager?.findViewByPosition(position)
    }

    open fun getOnItemClickListener(): OnItemClickListener? {
        return mAdapter?.getOnItemClickListener()
    }

    open fun setOnItemClickListener(listener: OnItemClickListener) {
        mOnItemClickListener = listener
        mAdapter?.setOnItemClickListener(listener)
    }

    open fun setOnCustomMessageDrawListener(listener: OnCustomMessageDrawListener) {
        mAdapter?.setOnCustomMessageDrawListener(listener)
    }

    open fun setMessageAdapter(adapter: MessageListAdapter) {
        super.setAdapter(adapter)
        mAdapter = adapter
        postSetAdapter(adapter)
    }

    protected abstract fun postSetAdapter(adapter: MessageListAdapter?)

    open fun addPopAction(action: PopMenuAction) {
        mMorePopActions.add(action)
    }

}